<?php
include("../config/config.php");

try {
	$db = Outils_Bd::getInstance()->getConnexion();
	
	$requeteTruncate = "TRUNCATE TABLE PopularityFriends";
	$db->exec($requeteTruncate);
	
	$requeteUser = "SELECT id_user FROM User";
	$sth = $db->query($requeteUser);
	$resultatsUser = $sth->fetchAll(PDO::FETCH_ASSOC);
	
	foreach($resultatsUser as $resultatU){
		$id_user=$resultatU['id_user'];
		$requeteMAJ = "SELECT id_title, id_user, ((SUM(score-5)*". POP_PONDERATION_SCORE ." )+ (COUNT(*)*". POP_PONDERATION_NBEVAL .") - (TIMESTAMPDIFF(DAY,time,NOW())*". POP_PONDERATION_TIME .")) as popularity FROM Rating WHERE score>0 AND id_user={$id_user} GROUP BY id_title  ORDER BY popularity DESC LIMIT 100";
		$sth = $db->query($requeteMAJ);	
		$resultatsT = $sth->fetchAll(PDO::FETCH_ASSOC);
		
		foreach($resultatsT as $resultatT){  
			$requeteT = "INSERT INTO PopularityFriends SET id_title=:id_title, popularity=:popularity, id_user=:id_user";
			$sth=$db->prepare($requeteT);
			$data=array(
				'popularity' => $resultatT['popularity'],
				'id_title' => $resultatT['id_title'],
				'id_user' => $resultatT['id_user']
			); 
			 $sth->execute($data);
		}
		
	}

} catch (Exception $e) {
	echo $e->getMessage();
	echo "<pre>{$e->getTraceAsString()}</pre>";
}


?>